package bom.example.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author X.I.O
 * @title: RequestUtils
 * @projectName springboot
 * @description: TODO
 * @date 2021/10/29 18:39
 */
public class Requestutils {

    /**
     * 获取当前会话中的HttpServletRequest
     *
     * @Title: getHttpServletRequest
     * @return: HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (sra != null) {
            return sra.getRequest();
        }
        return null;
    }

    /**
     * 获取当前请求地址，不含协议、主机、端口、部署路径及参数
     * @return
     */
    public static String getRequestUrl(HttpServletRequest request) {
        String uri = request.getRequestURI();
        String ctx = request.getContextPath();
        if(org.apache.commons.lang3.StringUtils.isBlank(uri)) {
            return "";
        }
        if(StringUtils.isBlank(ctx)){
            return uri;
        }
        return uri.substring(uri.indexOf(ctx)+ctx.length());
    }

    public static String getCliectIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        String[] arr = ip.split(",");
        String[] var3 = arr;
        int var4 = arr.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            String str = var3[var5];
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }

        return ip;
    }
}
